#include "oss_sdk.h"

void InitSDKEnvironment() {
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
}

void ExitSDKEnvironment() {
    aos_http_io_deinitialize();
}

void InitRequestsOptions(oss_request_options_t *options, size_t is_cname) {
    options -> config = oss_config_create(options -> pool);
    aos_str_set(&options -> config -> endpoint, "oss-cn-shanghai.aliyuncs.com");
    aos_str_set(&options -> config -> access_key_id, "LTAIkTMYwu1RvbQ5");
    aos_str_set(&options -> config -> access_key_secret, "3Pt64BiJQaqZZF0qaNmw25hDQBX5j7");
    options -> config -> is_cname = is_cname;

    options -> ctl = aos_http_controller_create(options -> pool, 0);
}

void OSSSDKUploadAPI(char *filename, char *objectname) {
    aos_pool_t *pool = NULL;
    oss_request_options_t *options = NULL;
    int is_cname = 0;

    aos_table_t *headers = NULL;
    aos_string_t bucket;
    aos_string_t object;
    aos_string_t file;
    aos_table_t *resp_headers = NULL;
    aos_status_t *s = NULL;

    aos_pool_create(&pool, NULL);

    options = oss_request_options_create(pool);
    InitRequestsOptions(options, is_cname);

    headers = aos_table_make(options -> pool, 1);
    apr_table_set(headers, OSS_CONTENT_TYPE, "text/xml");
    aos_str_set(&bucket, "cloudnote");
    aos_str_set(&object, objectname);
    aos_str_set(&file, filename);

    s = oss_put_object_from_file(options, &bucket, &object, &file, headers, &resp_headers);

    if (aos_status_is_ok(s)) {
        QMessageBox::about(NULL, "Upload Status", "Upload Successfully!");
    } else {
        QMessageBox::about(NULL, "Upload Status", "Upload Failed!\n" + QString::fromStdString(s -> error_msg));
    }

    aos_pool_destroy(pool);
}

void OSSSDKDownloadAPI() {
    return;
}

QStringList OSSSDKShowDataBaseAPI() {
    aos_pool_t *pool = NULL;
    oss_request_options_t *options = NULL;
    int is_cname = 0;

    aos_string_t bucket;
    oss_list_object_params_t *params = NULL;
    int max_ret = 1000;

    aos_table_t *resp_headers = NULL;
    aos_status_t *s = NULL;

    oss_list_object_content_t *content = NULL;
    char *key = NULL;

    QStringList keyList;

    aos_pool_create(&pool, NULL);

    options = oss_request_options_create(pool);
    InitRequestsOptions(options, is_cname);

    aos_str_set(&bucket, "cloudnote");
    params = oss_create_list_object_params(pool);
    params -> max_ret = max_ret;
    aos_str_set(&params->delimiter, "/");

    s = oss_list_object(options, &bucket, params, &resp_headers);

    if (aos_status_is_ok(s)) {
       aos_list_for_each_entry(oss_list_object_content_t, content, &params -> object_list, node) {
           key = apr_psprintf(pool, "%.*s", content -> key.len, content -> key.data);
           keyList.append(QString::fromLocal8Bit(key));
       }
    } else {
       QMessageBox::about(NULL, "Upload Status", "List Files Failed!");
    }

    aos_pool_destroy(pool);

    return keyList;
}
